package pide.core;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;


public class PrologInterface{
	
	private static PrologInterface instance = null;
	private String PROLOG_PATH;
	private String CONSULT_OPTION;
	private String URL_SEPARATOR;
	private boolean URL_QUOTE;
	public static String EOF = " /r/n";
	private PrologInterface()
	{
		
		Configuration conf = Configuration.getInstance();
		PROLOG_PATH = conf.get("prolog.home");
		CONSULT_OPTION = conf.get("prolog.consultoption");
		URL_SEPARATOR = conf.get("prolog.url.separator");
		URL_QUOTE=conf.getBoolean("prolog.url.quote");
		
	}
	
	
	public static PrologInterface getDefault(){
		if(instance==null)
			instance=new PrologInterface();
		return instance;
	}
	
	
	public void run(String ... consulted_files)
	{
		try {
		    // Execute command
		    String command = "cmd /K start cmd /K "+(PROLOG_PATH+" "+CONSULT_OPTION+" "+prepareURL(prepareConsultTemp(consulted_files).getAbsolutePath()));
//			String command =  "cmd /c start dir "+EOF;
		    Process child = Runtime.getRuntime().exec(command);
//		    OutputStream out = child.getOutputStream();
//
////		    out.write((PROLOG_PATH+" "+CONSULT_OPTION+" "+mainFile+EOF).getBytes());
//		    out.flush();
//		    out.write("dir /r/n".getBytes());
//		    out.close();
		    System.out.println(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String prepareURL(String url)
	{
		if(URL_SEPARATOR.equals("/"))		
			url=url.replace("\\", "/");		
		else		
			url=url.replace("/","\\");

		if(URL_QUOTE)
			return "\""+url+"\"";
		else
			return url;
	}
	
	private File prepareConsultTemp(String...consulted_files)
	{
		File f = null;
		try {
			f = File.createTempFile("$_consult_file_",".tmp");
			PrintWriter pw = new PrintWriter(f);
			for(String c :consulted_files)
			{
				pw.println(":-consult('"+prepareURL(c)+"').");
			}
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		
		
		return f;
	}
	
	public static void main(String[] args) {
//		Configuration.getInstance().add("prolog.home", "");
		PrologInterface.getDefault().run("C:/tmp/prova.pl", "C:/tmp/prova2.pl");
	}

	
	

	
	
}
